//
//  JFEnvironmentManager.m
//  moreEvn
//
//  Created by Alan Wang on 2018/9/10.
//  Copyright © 2018年 Alan Wang. All rights reserved.
//

#import "JFEnvironmentManager.h"
#import <UIKit/UIKit.h>
#import "JFDeviceInfo.h"
#import "JFBase.h"
@interface JFEnvironmentManager()
@property (nonatomic,strong) NSMutableDictionary * envMap;
@property (nonatomic,copy) NSString * filePath;
@property (nonatomic,copy) NSString * baseUrl;
@property (nonatomic,strong) WKWebView * wkwebview;
@end
@implementation JFEnvironmentManager
static JFEnvironmentManager* _instance = nil;

+(instancetype) shareInstance
{
    static dispatch_once_t onceToken ;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init] ;
        WEAKSELF
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            StrongSelf(weakSelf)
            [strongSelf sunlineWebView];
        });
    }) ;
    return _instance;
}
+(void)sunlineWebView{//web容器的初始化很耗时 300ms
    _instance.wkwebview = [[WKWebView alloc] init];
    WEAKSELF
    [_instance.wkwebview evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        StrongSelf(weakSelf)
        
        NSString * benben = [JFDeviceInfo isBenBen]?@"sunline-iOS":@"sunline_custom-iOS";
        NSString *userAgent = result;
        if ([userAgent rangeOfString:benben].location != NSNotFound) {
            return ;
        }
        NSString *newUserAgent = [NSString stringWithFormat:@"%@\\%@-%@",
                                  userAgent,
                                  benben,[JFDeviceInfo appVersion]];
        [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent" : newUserAgent, @"User-Agent" : newUserAgent}];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [strongSelf resetWebView:newUserAgent];
        
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        StrongSelf(weakSelf)
        [strongSelf remove];
    });
}

+(void)resetWebView:(NSString*)newUserAgent{
    if (@available(iOS 9.0, *)) {
         [_instance.wkwebview setCustomUserAgent:newUserAgent];
     } else {
         [_instance.wkwebview setValue:newUserAgent forKey:@"applicationNameForUserAgent"];
     }
}
+(void)remove{
    _instance.wkwebview = nil;
}
-(instancetype)init{
    self = [super init];
    if (self) {
        [self resetMap];
    }
    return self;
}
-(void)resetMap{
 
     @synchronized(self) {
         
       NSFileManager*fileManager =[NSFileManager defaultManager];
       NSError*error;
       NSArray*paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
       NSString*documentsDirectory =[paths objectAtIndex:0];
       NSString*filePath =[documentsDirectory stringByAppendingPathComponent:@"environment.plist"];
         
       BOOL flag = [fileManager fileExistsAtPath:filePath];

    
       if(flag== NO || _isDebug){
         if(flag){
               [fileManager removeItemAtPath:filePath error:&error];
          }
          NSString*resourcePath =[[NSBundle mainBundle] pathForResource:@"environment" ofType:@"plist"];
          [fileManager copyItemAtPath:resourcePath toPath:filePath error:&error];
           
       }else{
           NSDictionary * dict = [NSDictionary dictionaryWithContentsOfFile:filePath];
           _filePath = filePath;
           if(dict){
               NSString * env = [dict objectForKey:@"Env"];
               self.env = env;
               //把原来的文件删除
               [fileManager removeItemAtPath:filePath error:&error];
               //把包内的文件移动到沙盒
               NSString*resourcePath =[[NSBundle mainBundle] pathForResource:@"environment" ofType:@"plist"];
               [fileManager copyItemAtPath:resourcePath toPath:filePath error:&error];
               //读取沙盒内的文件 使用旧的环境值更新新的文件
               NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithContentsOfFile:self.filePath];
               if(dict){
                   dict[@"Env"] = env;
                   [dict writeToFile:self.filePath atomically:YES];
               }
           }
       }
         
       NSDictionary * dict = [NSDictionary dictionaryWithContentsOfFile:filePath];
       _filePath = filePath;
       if(dict){
          NSString * env = [dict objectForKey:@"Env"];
          self.env = env;
       }
         
     }
}
-(void)setIsDebug:(BOOL)isDebug{
    _isDebug = isDebug;
    if(isDebug){
        [self resetMap];
    }
}
+(NSString*)getUrlByKey:(NSString*)key{
  return [[JFEnvironmentManager shareInstance] getUrlByKey:key];
}
+(void)resetEnvironment:(NSString*)env updateFile:(BOOL)update block:(resetEnvironmentBlock)block{
    [[JFEnvironmentManager shareInstance] resetEnvironment:env updateFile:update block:block];
}




-(void)resetEnvironment:(NSString*)env  updateFile:(BOOL)update block:(resetEnvironmentBlock)block{
    [self setEnv:env];
    if(env != self.env){
        block(false);
    }else{
        if (update) {
            NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithContentsOfFile:self.filePath];
            if(dict){
                dict[@"Env"] = env;
                [dict writeToFile:self.filePath atomically:YES];
            }
        }
        block(true);
    }
}
-(void)setEnv:(NSString *)env{
    if (env&&env.length) {
        @synchronized(self.envMap) {
            NSDictionary * dict = [NSDictionary dictionaryWithContentsOfFile:self.filePath];
            if(dict){
                NSDictionary * serviceDict = [dict objectForKey:env];
                if(serviceDict){
                    [self.envMap removeAllObjects];
                   _env = env;
                    NSDictionary * baseServiceDict =  [serviceDict objectForKey:@"BaseService"];
                    NSDictionary * uriDict =  [serviceDict objectForKey:@"Uri"];
                    NSString * socketAddr = [serviceDict objectForKey:@"SocketService"];
                    self.socketAddr = socketAddr;
                    for (NSString * key in baseServiceDict.allKeys) {
                        NSString * baseServiceStr = baseServiceDict[key];
                        if(baseServiceStr&& baseServiceStr.length){
                            self.envMap[key] = baseServiceStr;
                            NSDictionary * uriItem = uriDict[key];
                            if (uriItem) {
                                for (NSString * uriPath in uriItem.allKeys) {
                                    self.envMap[uriPath] = [NSString stringWithFormat:@"%@%@",baseServiceStr,uriItem[uriPath]];
                                }
                            }
                        }
                        
                    }
                }
            }
            
        }
        
    }
}


-(NSString*)getUrlByKey:(NSString*)key{
    if(self.env && key && self.env.length && key.length){
         @synchronized(self.envMap) {
            return self.envMap[key];
         }
    }else{
        return @"";
    }
}
-(NSMutableDictionary*)envMap{
    if(!_envMap){
        _envMap = [[NSMutableDictionary alloc] init];
    }
    return _envMap;
}

//判断是否是生存环境
+(BOOL)isPro{
    if ([[JFEnvironmentManager shareInstance].env isEqualToString:@"Pro"] || [[JFEnvironmentManager shareInstance].env isEqualToString:@"ProHw"] || [[JFEnvironmentManager shareInstance].env isEqualToString:@"ProPC"]) {
        return YES;
    }
    return NO;
    
}
@end
